import sys
import requests
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QThread, pyqtSignal
from Ui_MainWindow import Ui_MainWindow  # 导入生成的UI模块

class DownloadWorker(QThread):
    progress_signal = pyqtSignal(int)
    status_signal = pyqtSignal(str)

    def __init__(self, url, save_path):
        super().__init__()
        self.url = url
        self.save_path = save_path

    def run(self):
        response = requests.get(self.url, stream=True)
        file_size = int(response.headers.get('content-length', 0))
        if file_size == 0:
            self.status_signal.emit("Error: Invalid file size")
            return

        with open(self.save_path, 'wb') as f:
            downloaded = 0
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
                    downloaded += len(chunk)
                    progress = int(100 * downloaded / file_size)
                    self.progress_signal.emit(progress)
            self.status_signal.emit("Download completed")

class DownloadPage(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.download_button.clicked.connect(self.start_download)

    def start_download(self):
        url = self.url_input.text().strip()
        save_path = "downloaded_video.mp4"  # 修改为实际保存路径

        if not url:
            self.status_label.setText("Error: Please enter a valid URL")
            return

        worker = DownloadWorker(url, save_path)
        worker.progress_signal.connect(self.update_progress)
        worker.status_signal.connect(self.update_status)
        worker.start()

    def update_progress(self, progress):
        self.progress_bar.setValue(progress)

    def update_status(self, status):
        self.status_label.setText(status)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DownloadPage()
    window.show()
    sys.exit(app.exec_())